package com.jadcon.bedbreakfast.domain;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

@Component
public class SuiteRepositoryInMemoryImpl implements SuiteRepository {


	public SuiteRepositoryInMemoryImpl() {
	}

	public List<Suite> getSuiteList() throws SQLException {
		
		List<Suite> suiteList = new ArrayList<Suite>();

		Connection con = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/bedandbreakfast", "root", "");
		Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
				ResultSet.CONCUR_UPDATABLE);
		ResultSet uprs = stmt
				.executeQuery("SELECT S_id, name, number, beds, cost, description, imageName FROM suite");

		if (uprs.isAfterLast() == false) {
	       uprs.afterLast();        
	}
	while (uprs.previous()) {

			String name = uprs.getString("name");
			int number = uprs.getInt("number");
			int beds = uprs.getInt("beds");
			int cost = uprs.getInt("cost");
			String description = uprs.getString("description");
			String imageName = uprs.getString("imageName");

			Suite suite = new Suite(name, number, beds, description, imageName,
					cost);

			suiteList.add(suite);

		}
		return suiteList;
	}

	
	public void save(Suite suite) {
	//TODO	suiteList.add(suite);

	}

	
	public Suite getNumber(int number) throws SQLException  {
		for (Suite suite : getSuiteList()) {
			if (suite.getNumber() == number) {
				return suite;
			}
		}
		return null;

	}
		
	public Suite getName(String name) throws SQLException {
		for (Suite suite : getSuiteList()) {
			if (suite.getName() == name) {
				return suite;
			}
		}
		return null;

	}

	public Suite getImageName(String name) throws SQLException {
		for (Suite suite : getSuiteList()) {
			if (suite.getImageName() == name) {
				return suite;
			}
		}
		return null;
	}

	public Suite getSuiteByNumber(int number) throws SQLException {
		Connection con = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/bedandbreakfast", "root", "");
		String sql = "SELECT name, number, beds, cost, description, imageName, S_id FROM suite where number=?";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setInt(1, number);
		ResultSet rs = pstmt.executeQuery();

		while (rs.next()) {
			String name = rs.getString("name");
			int number2 = rs.getInt("number");
			int beds = rs.getInt("beds");
			String description = rs.getString("description");
			String imageName = rs.getString("imageName");
			int cost = rs.getInt("cost");
			
			Suite suite = new Suite(name, number2, beds, description, imageName, cost);
			int number3 = suite.getNumber();
			System.out.println("Suite " + number3 + " was selected from database");

			return suite;

		}
		return null;
	}
	
}
